<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主讲教师" prop="principalId">
        <el-select
          filterable
          v-model="queryParams.principalId"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in teachers"
            :key="item.teacherId"
            :label="item.name"
            :value="item.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="辅助教师" prop="teacherIds">
        <el-select
          filterable
          v-model="queryParams.teacherIds"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in teachers"
            :key="item.teacherId"
            :label="item.name"
            :value="item.teacherId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学期" prop="semesterId">
        <el-select
          filterable
          v-model="queryParams.semesterId"
          placeholder="请选择学期"
          clearable
        >
          <el-option label="全部" :value="''"></el-option>
          <el-option
            v-for="item in schoolSemesterList"
            :key="item.semesterId"
            :label="item.semesterName"
            :value="item.semesterId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="$store.getters.roleId == 'schoolAdmin'"
        label="分院"
        prop="branchId"
      >
        <el-select
          filterable
          v-model="queryParams.branchId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="item in branchList"
            :key="item.branchId"
            :label="item.branchName"
            :value="item.branchId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="`${$majorName ? $majorName : '专业'}`"
        prop="majorNameId"
      >
        <el-select
          filterable
          v-model="queryParams.majorNameId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in queryParams_majors"
            :key="index"
            :label="item.majorName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程类型" prop="courseType">
        <el-select
          filterable
          v-model="queryParams.courseType"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="(item, index) of dict.type.course_type"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row v-if="false" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-if="activeIndex == '20' || activeIndex == '11'"
        >删除
        </el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- // 0.启用 1.禁用 2.待提交 3.待审核 4.已驳回 5.已到期 -->
    <div class="commonMenu">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
      >
        <el-menu-item index="01">正式在用</el-menu-item>

        <el-menu-item index="60">待组长审核</el-menu-item>
        <el-menu-item index="30">待分院审核</el-menu-item>
        <el-menu-item index="40">待学校审核</el-menu-item>
        <el-menu-item index="20">草稿</el-menu-item>
        <el-menu-item index="00">审核通过</el-menu-item>
        <el-menu-item index="50">已驳回</el-menu-item>
        <el-menu-item index="11">已停用</el-menu-item>
      </el-menu>
    </div>

    <el-table v-loading="loading" :data="postList">
      <el-table-column
        fixed
        show-overflow-tooltip
        label="分院名称"
        align="center"
        width="150"
        prop="branchName"
      />
      <el-table-column
        fixed
        show-overflow-tooltip
        label="课程名称"
        align="center"
        width="200"
        prop="courseName"
      />
      <el-table-column width="150" label="专业" align="center" prop="majorName">
      </el-table-column>
      <el-table-column
        width="120"
        label="课程类型"
        align="center"
        prop="status"
      >
        <template slot-scope="scope">
          <div
            v-if="item.value == scope.row.courseType + ''"
            v-for="(item, index) of dict.type.course_type"
            :key="index"
          >
            {{ item.label }}
          </div>
        </template>
      </el-table-column>
      <el-table-column width="120" label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <!-- // 0.启用 1.禁用 2.待提交 3.待审核 4.已驳回 5.已到期 -->
          <el-tag
            type="success"
            v-if="scope.row.status == 0 && activeIndex == '01'"
          >启用
          </el-tag
          >
          <el-tag
            type="success"
            v-if="scope.row.status == 0 && activeIndex == '00'"
          >已审核
          </el-tag
          >
          <el-tag type="danger" v-if="scope.row.status == 1">已停用</el-tag>
          <el-tag v-if="scope.row.status == 2">待提交</el-tag>
          <el-tag type="warning" v-if="scope.row.status == 3"
          >待分院审核
          </el-tag
          >
          <el-tag type="warning" v-if="scope.row.status == 4"
          >待学校审核
          </el-tag
          >
          <el-tag type="danger" v-if="scope.row.status == 5">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        witdh="120"
        :label="`${$hourAmount ? $hourAmount : '课时量'}`"
        align="center"
        prop="studyTime"
      />
      <el-table-column
        label="主讲教师"
        show-overflow-tooltip
        align="center"
        prop="principalName"
      />
      <el-table-column
        label="辅助教师"
        show-overflow-tooltip
        align="center"
        prop="teacherNames"
      />
      <el-table-column
        label="创建人"
        show-overflow-tooltip
        align="center"
        prop="creatorName"
      />
      <el-table-column
        label="创建时间"
        width="180"
        show-overflow-tooltip
        align="center"
        prop="createTime"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="最后操作时间"
        sortable
        align="center"
        show-overflow-tooltip
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评价" width="160" align="center">
        <template slot-scope="scope">
          <div style="text-align: left !important">
            <el-rate
              :value="scope.row.avgCourseStar"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            >
            </el-rate>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="160"
      >
        <!-- 00:状态解释 第一位数：0.启用 1.禁用 2.待提交 3.待分院审核 4.待学校审核 5.已驳回 第二位数：1：正式课程 0.草稿-->
        <template slot-scope="scope">
          <!-- 课程详情 按钮  -->
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-magic-stick"
            @click="handleUpdate(scope.row, 'detail', activeIndex)"
          >课程详情
          </el-button
          >
          <!-- 审核 按钮   <el-menu-item index="30">待分院审核</el-menu-item>
        <el-menu-item index="40">待学校审核</el-menu-item>-->
          <el-button
            v-preventReClick
            v-if="
              (activeIndex == '30' && $store.getters.roleId == 'branchAdmin') ||
              (activeIndex == '40' && $store.getters.roleId == 'schoolAdmin')
            "
            size="mini"
            type="text"
            icon="el-icon-thumb"
            @click="handleUpdate(scope.row, 'audit', activeIndex)"
          >
            审核
          </el-button
          >
          <!-- 复制 按钮  $store.getters.roleId=='admin' -->
          <el-button
            v-preventReClick
            v-if="
              activeIndex != '01' &&
              activeIndex != '11' &&
              $store.getters.roleId == 'admin'
            "
            size="mini"
            type="text"
            @click="handleCopy(scope.row)"
            icon="el-icon-connection"
          >
            复用
          </el-button>
          <!-- 更多下拉按钮  -->
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-button slot="reference" type="text" size="mini">
                更多<i class="el-icon-arrow-down"></i>
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <!-- 数据详情 按钮  -->
              <el-dropdown-item>
                <el-button
                  v-preventReClick
                  size="mini"
                  type="text"
                  icon="el-icon-magic-stick"
                  @click="handleDateDetail(scope.row)"
                >
                  数据详情
                </el-button>
              </el-dropdown-item>
              <!-- 驳回原因 按钮  -->
              <el-dropdown-item>
                <el-button
                  v-preventReClick
                  v-if="activeIndex == '50'"
                  size="mini"
                  type="text"
                  icon="el-icon-thumb"
                  @click="handleReason(scope.row)"
                >
                  驳回原因
                </el-button>
              </el-dropdown-item>
              <!-- 停用|启用  按钮  -->
              <el-dropdown-item>
                <el-button
                  v-preventReClick
                  v-if="activeIndex == '01' || activeIndex == '11'"
                  size="mini"
                  type="text"
                  icon="el-icon-open"
                  @click="
                    courseStatus(scope.row, scope.row.status == 0 ? 1 : 0)
                  "
                >
                  {{ scope.row.status == 0 ? '停用' : '启用' }}
                </el-button>
              </el-dropdown-item>
              <!-- 删除 按钮  -->
              <el-dropdown-item>
                <el-button
                  icon="el-icon-delete"
                  size="mini"
                  type="text"
                  v-if="activeIndex == '11'"
                  style="color: #e95756"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <rejectDia
      :type="3"
      :open.sync="rejectOpen"
      :propform="rejectform"
    ></rejectDia>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="课程复用"
      :visible="copyOpen"
      width="500px"
      append-to-body
      @close="cancelCopy"
    >
      <div style="color: #fda133; margin-bottom: 10px">
        <i class="el-icon-warning"></i>请选择复用学校及主讲教师
      </div>
      <el-form
        ref="copyForm"
        :model="copyForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="学校" prop="schoolId">
          <el-select
            filterable
            v-model="copyForm.schoolId"
            placeholder="请选择学校"
            clearable
          >
            <el-option
              v-for="item in schoolList"
              :key="item.schoolId"
              :label="item.schoolName"
              :value="item.schoolId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主讲教师" prop="principalId">
          <el-select
            filterable
            v-model="copyForm.principalId"
            placeholder="请选择主讲教师"
            clearable
          >
            <el-option
              v-for="item in teacherList"
              :key="item.teacherId"
              :label="item.name"
              :value="item.teacherId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex; justify-content: flex-end"
      >
        <el-button v-preventReClick @click="cancelCopy">取 消</el-button>
        <el-button v-preventReClick type="primary" @click="submitForm"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPost_branch
} from '@/api/schoolOrganization/organization'

import { getSchoolSemesterList } from '@/api/schoolSemester/schoolSemester'
import {
  allCourseList,
  delCourse,
  editCourse,
  copyCourseToOtherSchool
} from '@/api/course/course'
import { getMajorNameList } from '@/api/course/course'
import {
  listPost_teacher,
  getCreatorList
} from '@/api/schoolOrganization/teacher'
import { listPost_school } from '@/api/school/list'
import rejectDia from '../tea_course/components/rejectDia'

export default {
  name: 'Course',
  dicts: ['sys_normal_disable', 'course_type'],
  components: { rejectDia },
  data() {
    return {
      queryParams_majors: [],
      branchList: [],
      schoolSemesterList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // level
      level: [],
      // 查询参数
      activeIndex: '01',
      queryParams: {
        courseType: '',
        majorNameId: undefined,
        branchId: undefined,
        pageNum: 1,
        pageSize: 10,
        creatorId: undefined,
        principalId: undefined,
        courseName: undefined,
        status: 2,
        schoolId: undefined,
        semesterId: '',
        teacherIds: ''
      },
      //   教师列表
      teachers: [],
      creatorList: [],
      rejectOpen: false,
      rejectform: {},
      rowData: {},
      //复用弹框
      copyOpen: false,
      copyForm: {
        schoolId: '',
        principalId: ''
      },
      schoolName: '',
      teacherName: '',
      teacherList: [],
      schoolList: [],
      rules: {
        schoolId: [
          { required: true, message: '请选择学院', trigger: 'change' }
        ],
        principalId: [
          { required: true, message: '请选择主讲教师', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    'copyForm.schoolId': {
      handler(val) {
        if (val) {
          for (const branchListElement of this.schoolList) {
            if (branchListElement.schoolId == val) {
              this.schoolName = branchListElement.schoolName
            }
          }
          this.getTeacherByBranchId()
        }
      },
      deep: true
    },
    'copyForm.principalId': {
      handler(val) {
        for (const branchListElement of this.teacherList) {
          if (branchListElement.teacherId == val) {
            this.teacherName = branchListElement.name
          }
        }
      },
      deep: true
    }
  },
  activated() {
    this.getList()
  },
  async created() {
    this.getMajorNameList()
    this.getBranch()
    this.getTeacher()
    this.getCreatorList()
    await this.getSchoolSemester()
    this.getList()
  },
  methods: {
    async getMajorNameList() {
      let params = {
        pageNum: 1,
        pageSize: 9999
      }
      let res = await getMajorNameList(params)
      if (res.code == 200) {
        this.queryParams_majors = res.rows
      }
    },
    async getBranch() {
      let res = await listPost_branch({
        pageNum: 1,
        pageSize: 999,
        schoolId: this.$store.getters.schoolId
      })
      this.branchList = res.rows
    },
    async getSchoolSemester() {
      let res = await getSchoolSemesterList()
      const { code, rows } = res
      if (code == 200) {
        this.schoolSemesterList = rows
      }
    },
    getSchoolList() {
      let params = {
        pageNum: 1,
        pageSize: 9999
      }
      listPost_school(params).then((response) => {
        this.schoolList = response.rows
      })
    },
    // 获取教师列表
    getTeacherByBranchId() {
      listPost_teacher({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.copyForm.schoolId
      }).then((response) => {
        this.teacherList = response.rows
      })
    },
    cancelCopy() {
      this.$refs['copyForm'].resetFields()
      this.copyForm = {
        schoolId: '',
        principalId: ''
      }
      this.copyOpen = false
    },
    submitForm() {
      this.$refs['copyForm'].validate((valid) => {
        if (valid) {
          this.$confirm(
            `确认复用后，【${this.schoolName}】讲可以使用该课程教学，由【${this.teacherName}】进行编辑，是否确认继续？`,
            '复用确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(() => {
              this.copyCourseToOtherSchool()
            })
            .catch(() => {
              this.$modal.msgInfo('已取消')
            })
        }
      })
    },
    async copyCourseToOtherSchool() {
      const loading = this.$loading({
        lock: true,
        text: '正在处理…',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      try {
        let res = await copyCourseToOtherSchool(
          this.copyForm.schoolId,
          this.copyForm.principalId,
          this.rowData.courseId
        )
        const { code } = res
        if (code == 200) {
          this.$modal.msgSuccess('复制成功')
          this.copyOpen = false
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    handleCopy(row) {
      this.getSchoolList()
      this.rowData = row
      this.copyOpen = true
    },
    async getCreatorList() {
      let res = await getCreatorList()
      const { code, data } = res
      if (code == 200) {
        this.creatorList = data
      }
    },
    /* 驳回原因 */
    handleReason(row) {
      this.rejectform = row
      this.rejectOpen = true
    },
    // 获取教师列表 teacherId name
    getTeacher() {
      listPost_teacher({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId
      }).then((response) => {
        this.teachers = response.rows
      })
    },
    // 状态选择 查询列表
    handleSelect(key) {
      this.activeIndex = key
      this.getList()
    },
    /* 启用 停用课程 */
    courseStatus(item, status) {
      this.$confirm(
        `是否确认${status == 0 ? '启用' : '停用'}该课程?${
          status == 0 ? '' : '停用后该课程将无法使用'
        }`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          let data = JSON.parse(JSON.stringify(item))
          data.status = status
          let res = await editCourse(data)
          if (res.code == 200) {
            this.$modal.msgSuccess(`${status == 0 ? '启用' : '停用'}成功`)
            this.getList()
          }
        })
        .catch(() => {
        })
    },
    /* 查询课程列表 */
    async getList() {
      this.loading = true
      this.queryParams.schoolId = this.$store.getters.schoolId
      this.queryParams.status = this.activeIndex.slice(0, 1)
      this.queryParams.temporaryState = this.activeIndex.slice(1, 2)
      allCourseList(this.queryParams).then((response) => {
        response.rows.map((item) => {
          if (!item.avgCourseStar) {
            item.avgCourseStar = 0
          }
        })
        this.postList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: '/course/addCourse',
        query: {
          type: 'add'
        }
      })
    },
    /* 数据详情按钮 */
    handleDateDetail(row) {
      this.$router.push({
        path: '/course/courseDataDetail',
        query: {
          courseType: row.courseType,
          courseId: row.courseId
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row, type, activeIndex) {
      this.$router.push({
        path: '/course/addCourse',
        query: {
          courseTemporaryId: row.id,
          type: type,
          status: activeIndex,
          courseId: row.courseId,
          modelType: row.courseTemplate
        }
      })
    },
    /* 删除课程 */
    handleDelete(row) {
      this.$confirm(
        '删除课程后，课程将无法编辑，此操作不可撤销，是否确认删除该课程？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async() => {
          let res = await delCourse(row.courseId)
          const { code } = res
          if (code == 200) {
            this.$modal.msgSuccess('删除成功!')
            this.getList()
          }
        })
        .catch(() => {
          this.$modal.msgInfo('已取消')
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/post/export',
        {
          ...this.queryParams
        },
        `post_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-menu-item:hover {
  border-bottom: 1px solid #e6e6e6 !important;
}

::v-deep .el-menu--horizontal > .el-menu-item.is-active:hover {
  border-bottom: 2px solid #11a983 !important;
}
</style>
